<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>进入小程序中......</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .layout {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background: white;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            position: fixed;
            height: 100vh;
            overflow-y: auto;
            z-index: 1000;
        }

        .main-content {
            flex: 1;
            margin-left: 250px;
            padding: 20px;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
            padding: 20px;
        }

        .header h1 {
            font-size: 2em;
            margin-bottom: 10px;
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid #eee;
            text-align: center;
        }

        .sidebar-header h2 {
            color: #667eea;
            font-size: 1.5em;
        }

        .user-actions {
            margin-top: 15px;
            display: flex;
            gap: 8px;
            flex-direction: column;
        }

        .user-actions .btn {
            font-size: 12px;
            padding: 8px 12px;
        }

        .nav-menu {
            padding: 20px 0;
        }

        .nav-item {
            display: block;
            padding: 15px 20px;
            text-decoration: none;
            color: #333;
            transition: all 0.3s;
            border-left: 3px solid transparent;
        }

        .nav-item:hover {
            background: #f8f9fa;
            border-left-color: #667eea;
        }

        .nav-item.active {
            background: #667eea;
            color: white;
            border-left-color: #5a6fd8;
        }

        .content {
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .section {
            display: none;
        }

        .section.active {
            display: block;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 10px;
            border: 2px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }

        .btn {
            padding: 12px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            margin-right: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            position: relative;
            overflow: hidden;
        }

        .btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: left 0.5s;
        }

        .btn:hover::before {
            left: 100%;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-primary:hover {
            background: #5a6fd8;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #218838;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        .btn-warning {
            background: #ffc107;
            color: #212529;
        }

        .btn-warning:hover {
            background: #e0a800;
        }

        .btn-info {
            background: #17a2b8;
            color: white;
        }

        .btn-info:hover {
            background: #138496;
        }

        .form-text {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
            display: block;
        }

        .config-status {
            margin-top: 20px;
            padding: 15px;
            border-radius: 8px;
            display: none;
        }

        .config-status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .config-status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* 自定义确认对话框 */
        .confirm-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10000;
            backdrop-filter: blur(5px);
        }

        .confirm-dialog {
            background: white;
            border-radius: 15px;
            padding: 30px;
            max-width: 400px;
            width: 90%;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            text-align: center;
            animation: dialogSlideIn 0.3s ease-out;
        }

        @keyframes dialogSlideIn {
            from {
                opacity: 0;
                transform: translateY(-20px) scale(0.95);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .confirm-dialog h3 {
            margin: 0 0 20px 0;
            color: #333;
            font-size: 18px;
            font-weight: 600;
        }

        .confirm-dialog p {
            margin: 0 0 25px 0;
            color: #666;
            font-size: 16px;
            line-height: 1.5;
        }

        .confirm-buttons {
            display: flex;
            gap: 15px;
            justify-content: center;
        }

        .confirm-btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            min-width: 80px;
        }

        .confirm-btn.cancel {
            background: #f8f9fa;
            color: #6c757d;
            border: 2px solid #e9ecef;
        }

        .confirm-btn.cancel:hover {
            background: #e9ecef;
            border-color: #dee2e6;
        }

        .confirm-btn.confirm {
            background: #dc3545;
            color: white;
        }

        .confirm-btn.confirm:hover {
            background: #c82333;
            transform: translateY(-1px);
        }

        /* 修改密码模态框 */
        .password-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10000;
            backdrop-filter: blur(5px);
        }

        .password-dialog {
            background: white;
            border-radius: 15px;
            padding: 30px;
            max-width: 400px;
            width: 90%;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            animation: dialogSlideIn 0.3s ease-out;
        }

        .password-dialog h3 {
            margin: 0 0 20px 0;
            color: #333;
            font-size: 18px;
            font-weight: 600;
            text-align: center;
        }

        .password-form {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .password-form .form-group {
            margin-bottom: 0;
        }

        .password-form input {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .password-form input:focus {
            outline: none;
            border-color: #667eea;
        }

        .password-buttons {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin-top: 20px;
        }

        .qr-container {
            text-align: center;
            margin: 20px 0;
        }

        .qr-code {
            max-width: 300px;
            border: 2px solid #ddd;
            border-radius: 10px;
            padding: 10px;
            background: white;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
        }

        .stat-card h3 {
            font-size: 2em;
            margin-bottom: 5px;
        }

        .stat-card p {
            opacity: 0.9;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .table th, .table td {
            padding: 15px 12px;
            text-align: left;
            border-bottom: 1px solid #e9ecef;
        }

        .table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-weight: 600;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .table tr:hover {
            background: #f8f9fa;
            transform: translateY(-1px);
            transition: all 0.2s ease;
        }

        .table tr:last-child td {
            border-bottom: none;
        }

        .community-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .community-card {
            border: 2px solid #ddd;
            border-radius: 10px;
            padding: 20px;
            background: #f8f9fa;
        }

        .community-card h3 {
            margin-bottom: 10px;
            color: #333;
        }

        .community-actions {
            margin-top: 15px;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-active {
            background: #d4edda;
            color: #155724;
        }

        .status-inactive {
            background: #f8d7da;
            color: #721c24;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }

        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
        }

        .success {
            background: #d4edda;
            color: #155724;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
        }

        .filter-section {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 25px;
            border-radius: 15px;
            margin-bottom: 25px;
            border: 1px solid #dee2e6;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .filter-row {
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
        }

        .filter-item {
            flex: 0 0 auto;
            min-width: 120px;
        }

        .filter-select, .filter-input {
            width: 100%;
            padding: 10px 12px;
            border: 2px solid #e9ecef;
            border-radius: 6px;
            font-size: 14px;
            background: white;
            transition: all 0.3s ease;
            color: #495057;
        }

        .filter-select:focus, .filter-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .filter-select:hover, .filter-input:hover {
            border-color: #adb5bd;
        }

        .filter-actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-left: auto;
        }



        .records-section {
            margin-top: 30px;
        }

        .records-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .delete-actions {
            display: flex;
            gap: 10px;
        }

        .pagination {
            text-align: center;
            margin-top: 20px;
        }

        .pagination button {
            margin: 0 5px;
        }

        .record-actions {
            display: flex;
            gap: 5px;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 14px;
        }

        .device-info {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .device-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border: 1px solid rgba(255,255,255,0.2);
        }

        .device-badge.system {
            background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
            color: white;
        }

        .device-badge.software {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
        }

        .device-badge.network {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
            color: white;
        }

        .device-badge.device {
            background: linear-gradient(135deg, #dc3545 0%, #e83e8c 100%);
            color: white;
        }

        /* 筛选区域样式 */
        .filter-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            border: 1px solid #e9ecef;
        }

        .filter-row {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: center;
        }

        .filter-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .filter-item label {
            font-weight: 500;
            color: #495057;
            white-space: nowrap;
        }

        .filter-select {
            padding: 6px 12px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            background: white;
            font-size: 14px;
            min-width: 120px;
        }

        .filter-select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.25);
        }

        /* 时间段统计样式 */
        .time-slot-stats {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            border: 1px solid #e9ecef;
        }

        .time-slot-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .time-slot-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border: 1px solid #e9ecef;
        }

        .time-slot-card h4 {
            margin: 0 0 10px 0;
            color: #495057;
            font-size: 14px;
            font-weight: 600;
        }

        .time-slot-number {
            font-size: 2em;
            font-weight: bold;
            color: #667eea;
        }

        .time-slot-info {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .time-slot-time {
            font-size: 1.2em;
            font-weight: bold;
            color: #495057;
        }

        .time-slot-count {
            font-size: 1em;
            color: #6c757d;
        }

        .time-slot-chart {
            background: white;
            border-radius: 8px;
            padding: 20px;
            border: 1px solid #e9ecef;
        }

        .time-slot-bar {
            display: flex;
            align-items: end;
            gap: 2px;
            height: 100px;
            margin-top: 10px;
        }

        .time-slot-bar-item {
            flex: 1;
            background: #667eea;
            border-radius: 4px 4px 0 0;
            position: relative;
            min-width: 20px;
        }

        .time-slot-bar-item:hover {
            background: #5a6fd8;
        }

        .time-slot-bar-label {
            position: absolute;
            bottom: -25px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 10px;
            color: #6c757d;
            white-space: nowrap;
        }

        .time-slot-bar-value {
            position: absolute;
            top: -20px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 10px;
            color: #495057;
            font-weight: bold;
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: relative;
                height: auto;
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .layout {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="layout">
        <!-- 左侧边栏 -->
        <div class="sidebar">
                    <div class="sidebar-header">
            <h2>扫码管理</h2>
            <p id="userInfo">欢迎，<span id="username">管理员</span></p>
            <div class="user-actions">
                <button class="btn btn-sm btn-info" onclick="showChangePasswordModal()">修改密码</button>
                <button class="btn btn-sm btn-danger" onclick="logout()">退出登录</button>
            </div>
        </div>

            <nav class="nav-menu">
                <a href="#" class="nav-item active" onclick="showTab('statistics')">
                    📊 统计信息
                </a>
                <a href="#" class="nav-item" onclick="showTab('community-stats')">
                    🏢 地区统计
                </a>
                <a href="#" class="nav-item" onclick="showTab('qr')">
                    📱 二维码生成
                </a>
                <a href="#" class="nav-item" onclick="showTab('communities')">
                    🏘️ 地区管理
                </a>
                <a href="#" class="nav-item" onclick="showTab('system-config')">
                    ⚙️ 系统配置
                </a>
            </nav>
        </div>

        <!-- 主内容区域 -->
        <div class="main-content">
            <!-- 统计信息 -->
            <div id="statistics" class="content section active">
                <h2>统计信息</h2>
                <div id="statsGrid" class="stats-grid"></div>
                
                <h3>扫码记录</h3>



                <!-- 筛选和导出区域 -->
                <div class="filter-section">
                    <div class="filter-row">
                        <div class="filter-item">
                            <select id="filterCommunity" class="filter-select" onchange="onStatisticsFilterChange()">
                                <option value="">全部地区</option>
                            </select>
                        </div>
                        <div class="filter-item">
                            <select id="filterYear" class="filter-select" onchange="onStatisticsFilterChange()">
                                <option value="">全部年份</option>
                            </select>
                        </div>
                        <div class="filter-item">
                            <select id="filterJumpLinkName" class="filter-select" onchange="onStatisticsFilterChange()">
                                <option value="">全部跳转链接</option>
                            </select>
                        </div>
                        <div class="filter-item">
                            <select id="filterDate" class="filter-select" onchange="onStatisticsFilterChange()">
                                <option value="">全部日期</option>
                            </select>
                        </div>
                        <div class="filter-actions">
                            <button class="btn btn-info" onclick="clearFilters()">清除筛选</button>
                            <button class="btn btn-success" onclick="exportAllRecords()">导出全部</button>
                            <button class="btn btn-danger" onclick="deleteSelectedRecords()">删除选中</button>
                        </div>
                    </div>
                </div>
                
                <table class="table">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAll" onclick="toggleSelectAll()"></th>
                            <th>时间</th>
                            <th>地区</th>
                            <th>地址信息</th>
                            <th>设备信息</th>
                            <th>跳转链接</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="recordsTable">
                    </tbody>
                </table>
                
                <div id="pagination" class="pagination"></div>
            </div>

            <!-- 地区统计 -->
            <div id="community-stats" class="content section">
                <h2 style="margin-bottom: 10px;">各地区扫码记录</h2>
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <div class="filter-section" style="margin-bottom: 0; flex: 1;">
                        <div class="filter-row" style="flex-wrap:nowrap; align-items:center;">
                            <div class="filter-item">
                                <select id="sortBy" class="filter-select" onchange="loadCommunityStats()">
                                    <option value="total">按总扫码次数</option>
                                    <option value="today">按今日扫码次数</option>
                                </select>
                            </div>
                            <div class="filter-item">
                                <select id="sortOrder" class="filter-select" onchange="loadCommunityStats()">
                                    <option value="desc">降序</option>
                                    <option value="asc">升序</option>
                                </select>
                            </div>
                            <div class="filter-item">
                                <select id="communityFilterYear" class="filter-select" onchange="onYearChange()">
                                    <option value="">全部年份</option>
                                </select>
                            </div>
                            <div class="filter-item">
                                <select id="communityFilterMonth" class="filter-select" onchange="onMonthChange()">
                                    <option value="">全部月份</option>
                                </select>
                            </div>
                            <div class="filter-item">
                                <select id="communityFilterDate" class="filter-select" onchange="onDateChange()">
                                    <option value="">全部日期</option>
                                </select>
                            </div>
                            <div class="filter-item">
                                <select id="communityFilterJumpLinkName" class="filter-select" onchange="loadCommunityStats()">
                                    <option value="">全部跳转链接</option>
                                </select>
                            </div>
                            <div class="filter-actions" style="margin-left: 10px;">
                                <button class="btn btn-info" onclick="exportCommunityStats()">导出地区统计</button>
                                <button class="btn btn-warning" onclick="resetCommunityStats()">重置筛选</button>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 时间段统计（默认显示） -->
                <div id="timeSlotStats" class="time-slot-stats" style="margin-bottom: 20px;">
                    <h3>时间段统计</h3>
                    <div class="time-slot-grid">
                        <div class="time-slot-card">
                            <h4>扫码总次数</h4>
                            <div class="time-slot-number" id="dailyTotalScans">0</div>
                        </div>
                        <div class="time-slot-card">
                            <h4>最高扫码时间段</h4>
                            <div class="time-slot-info">
                                <div class="time-slot-time" id="maxTimeSlot">-</div>
                                <div class="time-slot-count" id="maxTimeSlotCount">0次</div>
                            </div>
                        </div>
                        <div class="time-slot-card">
                            <h4>最低扫码时间段</h4>
                            <div class="time-slot-info">
                                <div class="time-slot-time" id="minTimeSlot">-</div>
                                <div class="time-slot-count" id="minTimeSlotCount">0次</div>
                            </div>
                        </div>
                        <div class="time-slot-card">
                            <h4>最高扫码地区</h4>
                            <div class="time-slot-info">
                                <div class="time-slot-time" id="maxCommunity">-</div>
                                <div class="time-slot-count" id="maxCommunityCount">0次</div>
                            </div>
                        </div>
                        <div class="time-slot-card">
                            <h4>最低扫码地区</h4>
                            <div class="time-slot-info">
                                <div class="time-slot-time" id="minCommunity">-</div>
                                <div class="time-slot-count" id="minCommunityCount">0次</div>
                            </div>
                        </div>
                    </div>
                    <div class="time-slot-chart" id="timeSlotChart"></div>
                </div>
                <table class="table">
                    <thead>
                        <tr>
                            <th>地区名称</th>
                            <th id="totalScansHeader">总扫码次数</th>
                            <th id="todayScansHeader">今日扫码次数</th>
                            <th>跳转链接</th>
                        </tr>
                    </thead>
                    <tbody id="statsTable">
                    </tbody>
                </table>
        </div>

        <!-- 二维码生成 -->
        <div id="qr" class="content section">
            <h2>生成二维码</h2>
            <div class="form-group">
                <label for="communitySelect">选择地区：</label>
                <select id="communitySelect">
                    <option value="">请选择地区</option>
                </select>
            </div>
            <div class="form-group">
                <label for="jumpLinkSelect">选择跳转链接：</label>
                <select id="jumpLinkSelect">
                    <option value="">请选择跳转链接</option>
                </select>
            </div>
            <button class="btn btn-primary" onclick="generateQR()">生成二维码</button>
            <div id="qrResult" class="qr-container" style="display: none;">
                <h3>生成的二维码</h3>
                <img id="qrImage" class="qr-code" alt="二维码">
                <p id="qrInfo"></p>
            </div>
        </div>

            <!-- 地区管理 -->
        <div id="communities" class="content section">
                <h2>地区管理</h2>
            <div class="form-group">
                    <label for="newCommunityName">地区名称：</label>
                    <input type="text" id="newCommunityName" placeholder="请输入地区名称">
            </div>
                <button class="btn btn-success" onclick="addCommunity()">添加地区</button>
            
            <div id="communitiesList" class="community-list"></div>
        </div>

            <!-- 系统配置 -->
            <div id="system-config" class="content section">
                <h2>系统配置</h2>
                <div class="form-group">
                    <label>跳转链接配置：</label>
                    <div id="jumpLinksList"></div>
                    <button class="btn btn-success" onclick="addJumpLink()">添加跳转链接</button>
                </div>
                <div class="form-group">
                    <label for="baseUrl">基础URL：</label>
                    <input type="url" id="baseUrl" placeholder="请输入基础URL，例如：https://yourdomain.com">
                    <small class="form-text">系统的基础访问地址，用于生成二维码链接</small>
                </div>
                <div class="form-group">
                    <label for="tencentMapKey">腾讯地图Key：</label>
                    <input type="text" id="tencentMapKey" placeholder="请输入腾讯地图WebService Key">
                    <small class="form-text">用于IP定位，申请地址：https://lbs.qq.com/dev/console/key/manage</small>
                </div>
                <div class="form-group">
                    <label for="baiduMapAk">百度地图AK：</label>
                    <input type="text" id="baiduMapAk" placeholder="请输入百度地图AK">
                    <small class="form-text">用于逆地理编码，申请地址：https://lbsyun.baidu.com/apiconsole/key</small>
                </div>
                <button class="btn btn-primary" onclick="saveSystemConfig()">保存配置</button>
                <button class="btn btn-info" onclick="loadSystemConfig()">重新加载</button>
                <div id="configStatus" class="config-status"></div>
            </div>
        </div>
    </div>

    <!-- 修改密码模态框 -->
    <div id="passwordModal" class="password-modal" style="display: none;">
        <div class="password-dialog">
            <h3>修改密码</h3>
            <div id="passwordError" class="error" style="display: none; margin-bottom: 15px;"></div>
            <form class="password-form" onsubmit="handleChangePassword(event)">
                <div class="form-group">
                    <label for="currentPassword">当前密码</label>
                    <input type="password" id="currentPassword" required>
                </div>
                <div class="form-group">
                    <label for="newPassword">新密码</label>
                    <input type="password" id="newPassword" required minlength="6">
                </div>
                <div class="form-group">
                    <label for="confirmPassword">确认新密码</label>
                    <input type="password" id="confirmPassword" required minlength="6">
                </div>
                <div class="password-buttons">
                    <button type="button" class="btn btn-warning" onclick="closePasswordModal()">取消</button>
                    <button type="submit" class="btn btn-primary">确认修改</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let currentPage = 1;
        let currentLimit = 20;
        let currentFilters = {};
        let selectedRecords = new Set();
        let availableDates = [];
        let currentUser = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 检查登录状态
            if (localStorage.getItem('isLoggedIn') !== 'true') {
                window.location.href = '/login';
                return;
            }
            // 显示用户名
            const username = localStorage.getItem('username') || '管理员';
            document.getElementById('username').textContent = username;
            
            // 初始化表格标题
            updateTableHeaders('', '', '');
            
            loadCommunities();
            loadStatistics();
            loadCommunityStats();
            loadRecords();
            loadAvailableDates(); // 加载统计信息的可用日期
            loadCommunityAvailableDates(); // 加载地区统计的可用日期
            loadSystemConfig();
        });

        // 检查登录状态
        async function checkAuthStatus() {
            try {
                const response = await fetch('/api/auth/status');
                const data = await response.json();
                
                if (data.success && data.isLoggedIn) {
                    currentUser = data.user;
                    document.getElementById('username').textContent = currentUser.username;
                    loadCommunities();
                    loadStatistics();
                    loadCommunityStats();
                    loadRecords();
                    loadAvailableDates();
                    loadSystemConfig();
                } else {
                    window.location.href = '/login';
                }
            } catch (error) {
                console.error('检查登录状态失败:', error);
                window.location.href = '/login';
            }
        }

        // 切换标签页
        function showTab(tabName) {
            // 隐藏所有内容
            document.querySelectorAll('.section').forEach(section => {
                section.classList.remove('active');
            });
            
            // 移除所有导航项的active类
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            
            // 显示选中的内容
            document.getElementById(tabName).classList.add('active');
            
            // 添加active类到选中的导航项
            event.target.classList.add('active');
            
            // 根据标签页加载数据
            if (tabName === 'statistics') {
                loadStatistics();
                loadRecords();
            } else if (tabName === 'community-stats') {
                loadCommunityStats();
            } else if (tabName === 'system-config') {
                loadSystemConfig();
            }
        }

        // 加载地区列表
        async function loadCommunities() {
            try {
                const response = await fetch('/api/communities');
                const data = await response.json();
                
                if (data.success) {
                    const communities = data.communities;
                    
                    // 更新二维码生成页面的选择框
                    const qrSelect = document.getElementById('communitySelect');
                    qrSelect.innerHTML = '<option value="">请选择地区</option>';
                    communities.forEach(community => {
                        if (community.active) {
                            const option = document.createElement('option');
                            option.value = community.id;
                            option.textContent = community.name;
                            qrSelect.appendChild(option);
                        }
                    });
                    
                    // 更新筛选选择框
                    const filterSelect = document.getElementById('filterCommunity');
                    filterSelect.innerHTML = '<option value="">全部地区</option>';
                    communities.forEach(community => {
                        const option = document.createElement('option');
                        option.value = community.id;
                        option.textContent = community.name;
                        filterSelect.appendChild(option);
                    });
                    

                    
                    // 更新地区管理页面
                    displayCommunities(communities);
                }
            } catch (error) {
                console.error('加载地区列表失败:', error);
                showError('加载地区列表失败');
            }
        }

        // 显示地区列表
        function displayCommunities(communities) {
            const container = document.getElementById('communitiesList');
            container.innerHTML = '';
            
            communities.forEach(community => {
                const card = document.createElement('div');
                card.className = 'community-card';
                card.innerHTML = `
                    <h3>${community.name}</h3>
                    <p>状态: <span class="status-badge ${community.active ? 'status-active' : 'status-inactive'}">
                        ${community.active ? '启用' : '禁用'}
                    </span></p>
                    <div class="community-actions">
                        <button class="btn btn-warning" onclick="toggleCommunity(${community.id}, ${!community.active})">
                            ${community.active ? '禁用' : '启用'}
                        </button>
                        <button class="btn btn-danger" onclick="deleteCommunity(${community.id})">删除</button>
                    </div>
                `;
                container.appendChild(card);
            });
        }

        // 生成二维码
        async function generateQR() {
            const communityId = document.getElementById('communitySelect').value;
            const jumpLinkName = document.getElementById('jumpLinkSelect').value;
            if (!communityId || !jumpLinkName) {
                showError('请选择地区和小程序');
                return;
            }
            // 这里假设后端支持 jumpLinkName 参数
            const response = await fetch(`/api/qrcode?communityId=${communityId}&jumpLinkName=${encodeURIComponent(jumpLinkName)}`);
            const data = await response.json();
            if (data.success) {
                document.getElementById('qrResult').style.display = 'block';
                document.getElementById('qrImage').src = data.qrCode;
                // 修正：二维码跳转链接/jump要带上jumpLinkName参数
                let jumpUrl = data.jumpUrl;
                if (jumpUrl.indexOf('jumpLinkName=') === -1) {
                    jumpUrl += (jumpUrl.indexOf('?') > -1 ? '&' : '?') + 'jumpLinkName=' + encodeURIComponent(jumpLinkName);
                }
                document.getElementById('qrInfo').textContent = '跳转链接：' + jumpUrl;
            } else {
                showError(data.error || '生成二维码失败');
            }
        }

        // 添加地区
        async function addCommunity() {
            const name = document.getElementById('newCommunityName').value.trim();
            
            if (!name) {
                showError('请输入地区名称');
                return;
            }
            
            try {
                const response = await fetch('/api/communities', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ name })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess('地区添加成功');
                    document.getElementById('newCommunityName').value = '';
                    loadCommunities();
                } else {
                    showError(data.error);
                }
            } catch (error) {
                console.error('添加地区失败:', error);
                showError('添加地区失败');
            }
        }

        // 切换地区状态
        async function toggleCommunity(id, active) {
            try {
                const response = await fetch(`/api/communities/${id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ active })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess(`地区${active ? '启用' : '禁用'}成功`);
                    loadCommunities();
                } else {
                    showError(data.error);
                }
            } catch (error) {
                console.error('更新地区状态失败:', error);
                showError('更新地区状态失败');
            }
        }

        // 删除地区
        async function deleteCommunity(id) {
            const confirmed = await showConfirmDialog('确定要删除这个地区吗？');
            if (!confirmed) {
                return;
            }
            
            try {
                const response = await fetch(`/api/communities/${id}`, {
                    method: 'DELETE'
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess('地区删除成功');
                    loadCommunities();
                } else {
                    showError(data.error);
                }
            } catch (error) {
                console.error('删除地区失败:', error);
                showError('删除地区失败');
            }
        }

        // 加载统计信息
        async function loadStatistics() {
            const params = new URLSearchParams();
            if (currentFilters.communityId) params.append('communityId', currentFilters.communityId);
            if (currentFilters.startDate) params.append('startDate', currentFilters.startDate);
            if (currentFilters.endDate) params.append('endDate', currentFilters.endDate);
            if (currentFilters.startTime) params.append('startTime', currentFilters.startTime);
            if (currentFilters.endTime) params.append('endTime', currentFilters.endTime);
            if (currentFilters.jumpLinkName) params.append('jumpLinkName', currentFilters.jumpLinkName);
            if (currentFilters.year) params.append('year', currentFilters.year);
            const response = await fetch(`/api/statistics?${params.toString()}`);
            const data = await response.json();
            if (data.success) {
                displayStatistics(data.statistics);
            } else {
                showError(data.error);
            }
        }

        // 显示统计信息
        function displayStatistics(stats) {
            // 显示统计卡片
            const statsGrid = document.getElementById('statsGrid');
            statsGrid.innerHTML = `
                <div class="stat-card">
                    <h3>${stats.totalScans}</h3>
                    <p>总扫码次数</p>
                </div>
                <div class="stat-card">
                    <h3>${stats.todayScans}</h3>
                    <p>今日扫码次数</p>
                </div>
                <div class="stat-card">
                    <h3>${stats.communityStats.length}</h3>
                    <p>地区数量</p>
                </div>
            `;
        }

        // 顶部统计卡片渲染
        function renderCommunityStatsGrid(stats) {}

        // 修改loadCommunityStats，移除顶部统计卡片渲染
        async function loadCommunityStats() {
            try {
                const sortBy = document.getElementById('sortBy').value;
                const sortOrder = document.getElementById('sortOrder').value;
                const year = document.getElementById('communityFilterYear').value;
                const month = document.getElementById('communityFilterMonth').value;
                const date = document.getElementById('communityFilterDate').value;
                const jumpLinkName = document.getElementById('communityFilterJumpLinkName').value;
                updateTableHeaders(year, month, date);
                const params = new URLSearchParams({ sortBy: sortBy, order: sortOrder });
                if (year) params.append('year', year);
                if (month) params.append('month', month);
                if (date) params.append('date', date);
                if (jumpLinkName) params.append('jumpLinkName', jumpLinkName);
                const response = await fetch(`/api/community-statistics?${params.toString()}`);
                const data = await response.json();
                if (data.success) {
                    displayCommunityStats(data.communityStats);
                    displayTimeSlotStats(data.timeSlotStats);
                } else {
                    showError('加载地区统计失败: ' + data.error);
                }
            } catch (error) {
                console.error('加载地区统计失败:', error);
                showError('加载地区统计失败: ' + error.message);
            }
        }

        // 显示地区统计
        function displayCommunityStats(stats) {
            const statsTable = document.getElementById('statsTable');
            statsTable.innerHTML = '';
            stats.forEach(stat => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${stat.name}</td>
                    <td>${stat.totalScans}</td>
                    <td>${stat.todayScans !== undefined ? stat.todayScans : ''}</td>
                    <td>${stat.jumpLinkName || ''}</td>
                `;
                statsTable.appendChild(row);
            });
        }
        
        // 更新表格标题
        function updateTableHeaders(year, month, date) {
            const totalScansHeader = document.getElementById('totalScansHeader');
            const todayScansHeader = document.getElementById('todayScansHeader');
            
            if (year && !month && !date) {
                // 只选择年份时
                totalScansHeader.textContent = '当年扫码次数';
                todayScansHeader.textContent = '当年扫码次数';
            } else if (year && month && !date) {
                // 选择年份+月份时
                totalScansHeader.textContent = '当年扫码次数';
                todayScansHeader.textContent = '当月扫码次数';
            } else if (year && month && date) {
                // 选择年份+月份+日期时
                totalScansHeader.textContent = '当年扫码次数';
                todayScansHeader.textContent = '当日扫码次数';
            } else if (month && !year && !date) {
                // 只选择月份时
                totalScansHeader.textContent = '当年总次数';
                todayScansHeader.textContent = '当月扫码次数';
            } else if (date && !year && !month) {
                // 只选择日期时
                totalScansHeader.textContent = '当年总次数';
                todayScansHeader.textContent = '当日扫码次数';
            } else if (!year && month && date) {
                totalScansHeader.textContent = '当年扫码次数';
                todayScansHeader.textContent = '当日扫码次数';
            } else {
                // 没有筛选时
                totalScansHeader.textContent = '总扫码次数';
                todayScansHeader.textContent = '今日扫码次数';
            }
        }

        // 显示时间段统计
        function displayTimeSlotStats(timeSlotStats) {
            const timeSlotStatsDiv = document.getElementById('timeSlotStats');
            if (!timeSlotStats) {
                timeSlotStatsDiv.style.display = 'none';
                return;
            }
            timeSlotStatsDiv.style.display = 'block';
            // 更新统计卡片
            document.getElementById('dailyTotalScans').textContent = timeSlotStats.totalScans;
            document.getElementById('maxTimeSlot').textContent = timeSlotStats.maxTimeSlot.timeSlot;
            document.getElementById('maxTimeSlotCount').textContent = `${timeSlotStats.maxTimeSlot.count}次`;
            document.getElementById('minTimeSlot').textContent = timeSlotStats.minTimeSlot.timeSlot;
            document.getElementById('minTimeSlotCount').textContent = `${timeSlotStats.minTimeSlot.count}次`;
            // 更新地区统计卡片
            if (timeSlotStats.maxCommunity) {
                document.getElementById('maxCommunity').textContent = timeSlotStats.maxCommunity.name;
                document.getElementById('maxCommunityCount').textContent = `${timeSlotStats.maxCommunity.scanCount}次`;
            }
            if (timeSlotStats.minCommunity) {
                document.getElementById('minCommunity').textContent = timeSlotStats.minCommunity.name;
                document.getElementById('minCommunityCount').textContent = `${timeSlotStats.minCommunity.scanCount}次`;
            }
            // 生成柱状图（只显示当前小程序的数据）
            const chartDiv = document.getElementById('timeSlotChart');
            chartDiv.innerHTML = '<h4>时间段分布图</h4>';
            const barContainer = document.createElement('div');
            barContainer.className = 'time-slot-bar';
            // 只显示当前小程序的数据（后端已按筛选返回）
            timeSlotStats.timeSlots.forEach(slot => {
                const maxCount = Math.max(...timeSlotStats.timeSlots.map(s => s.count));
                const height = maxCount > 0 ? (slot.count / maxCount) * 80 : 0;
                const barItem = document.createElement('div');
                barItem.className = 'time-slot-bar-item';
                barItem.style.height = `${height}px`;
                const label = document.createElement('div');
                label.className = 'time-slot-bar-label';
                label.textContent = slot.timeSlot;
                const value = document.createElement('div');
                value.className = 'time-slot-bar-value';
                value.textContent = slot.count;
                barItem.appendChild(label);
                barItem.appendChild(value);
                barContainer.appendChild(barItem);
            });
            chartDiv.appendChild(barContainer);
        }

        // 加载地区统计可用日期（统一用 /api/records/years-dates）
        async function loadCommunityAvailableDates(selectedYear = null, selectedMonth = null) {
            try {
                console.log('开始加载可用日期，参数:', { selectedYear, selectedMonth });
                const params = new URLSearchParams();
                if (selectedYear) {
                    params.append('year', selectedYear);
                }
                if (selectedMonth) {
                    params.append('month', selectedMonth);
                }
                const url = `/api/records/years-dates?${params.toString()}`;
                console.log('请求URL:', url);
                const response = await fetch(url);
                const data = await response.json();
                console.log('API响应:', data);
                const yearSelect = document.getElementById('communityFilterYear');
                const monthSelect = document.getElementById('communityFilterMonth');
                const dateSelect = document.getElementById('communityFilterDate');
                // 清空现有选项（保留默认选项）
                yearSelect.innerHTML = '<option value="">全部年份</option>';
                monthSelect.innerHTML = '<option value="">全部月份</option>';
                dateSelect.innerHTML = '<option value="">全部日期</option>';
                // 添加年份选项
                if (data.years && data.years.length > 0) {
                    data.years.forEach(year => {
                        const option = document.createElement('option');
                        option.value = year;
                        option.textContent = year;
                        yearSelect.appendChild(option);
                    });
                }
                // 添加月份选项
                if (data.months && data.months.length > 0) {
                    data.months.forEach(month => {
                        const option = document.createElement('option');
                        option.value = month;
                        if (selectedYear) {
                            option.textContent = month.split('-')[1];
                        } else {
                            option.textContent = month;
                        }
                        monthSelect.appendChild(option);
                    });
                }
                // 添加日期选项
                if (data.dates && data.dates.length > 0) {
                    data.dates.forEach(date => {
                        const option = document.createElement('option');
                        option.value = date;
                        if ((selectedYear && selectedMonth) || (!selectedYear && selectedMonth)) {
                            option.textContent = date.split('-')[2];
                        } else if (selectedYear) {
                            option.textContent = date.substring(5);
                        } else {
                            option.textContent = date;
                        }
                        dateSelect.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('加载可用日期失败:', error);
            }
        }

        // 年份变化处理
        async function onYearChange() {
            const year = document.getElementById('communityFilterYear').value;
            const monthSelect = document.getElementById('communityFilterMonth');
            const dateSelect = document.getElementById('communityFilterDate');
            
            // 清空月份和日期选择
            monthSelect.value = '';
            dateSelect.value = '';
            
            // 重新加载月份和日期选项（根据选择的年份筛选）
            await loadCommunityAvailableDates(year);
            
            // 重新设置年份选择（因为重新加载选项会清空选择）
            if (year) {
                document.getElementById('communityFilterYear').value = year;
            }
            
            // 重新加载地区统计
            loadCommunityStats();
        }

        // 月份变化处理
        async function onMonthChange() {
            const year = document.getElementById('communityFilterYear').value;
            const month = document.getElementById('communityFilterMonth').value;
            const dateSelect = document.getElementById('communityFilterDate');
            
            // 清空日期选择
            dateSelect.value = '';
            
            // 重新加载日期选项（根据选择的年份和月份筛选）
            await loadCommunityAvailableDates(year, month);
            
            // 重新设置年份和月份选择（因为重新加载选项会清空选择）
            if (year) {
                document.getElementById('communityFilterYear').value = year;
            }
            if (month) {
                document.getElementById('communityFilterMonth').value = month;
            }
            
            // 重新加载地区统计
            loadCommunityStats();
        }

        // 日期变化处理
        function onDateChange() {
            // 直接重新加载地区统计，不清空年份和月份选择
            loadCommunityStats();
        }

        // 重置地区统计筛选
        async function resetCommunityStats() {
            document.getElementById('sortBy').value = 'total';
            document.getElementById('sortOrder').value = 'desc';
            document.getElementById('communityFilterYear').value = '';
            document.getElementById('communityFilterMonth').value = '';
            document.getElementById('communityFilterDate').value = '';
            // 小程序下拉框重置为第一个
            const jumpSelect = document.getElementById('communityFilterJumpLinkName');
            if (jumpSelect && jumpSelect.options.length > 1) {
                jumpSelect.selectedIndex = 0;
            } else if (jumpSelect) {
                jumpSelect.selectedIndex = 1;
            }
            await loadCommunityAvailableDates();
            loadCommunityStats();
        }

        // 应用筛选
        function applyFilters() {
            const communityId = document.getElementById('filterCommunity').value;
            const filterDate = document.getElementById('filterDate').value;
            const jumpLinkName = document.getElementById('filterJumpLinkName').value;
            const year = document.getElementById('filterYear').value;
            currentFilters = {};
            if (communityId) currentFilters.communityId = communityId;
            if (filterDate) currentFilters.date = filterDate;
            if (jumpLinkName) currentFilters.jumpLinkName = jumpLinkName;
            if (year) currentFilters.year = year;
            loadRecords(1);
            loadStatistics();
        }

        // 加载可用日期
        async function loadAvailableDates() {
            try {
                const communityId = document.getElementById('filterCommunity').value;
                const params = new URLSearchParams();
                if (communityId) {
                    params.append('communityId', communityId);
                }
                
                const response = await fetch(`/api/records/dates?${params.toString()}`);
                const data = await response.json();
                
                if (data.success) {
                    availableDates = data.dates;
                    updateDateSelects();
                }
            } catch (error) {
                console.error('加载日期列表失败:', error);
            }
        }

        // 更新日期选择框
        function updateDateSelects() {
            const filterDateSelect = document.getElementById('filterDate');
            
            // 清空现有选项
            filterDateSelect.innerHTML = '<option value="">全部日期</option>';
            
            // 添加日期选项
            availableDates.forEach(date => {
                const dateStr = new Date(date).toLocaleDateString('zh-CN');
                
                // 筛选日期选择框
                const filterOption = document.createElement('option');
                filterOption.value = date;
                filterOption.textContent = dateStr;
                filterDateSelect.appendChild(filterOption);
            });
        }

        // 清除筛选
        function clearFilters() {
            document.getElementById('filterCommunity').value = '';
            document.getElementById('filterDate').value = '';
            document.getElementById('filterJumpLinkName').value = '';
            document.getElementById('filterYear').value = '';
            currentFilters = {};
            selectedRecords.clear();
            updateSelectAllCheckbox();
            loadRecords(1);
            loadStatistics();
            loadAvailableDates();
        }

        // 加载扫码记录
        async function loadRecords(page = 1) {
            const params = new URLSearchParams({
                page: page,
                limit: currentLimit
            });
            if (currentFilters.communityId) params.append('communityId', currentFilters.communityId);
            if (currentFilters.date) params.append('date', currentFilters.date);
            if (currentFilters.jumpLinkName) params.append('jumpLinkName', currentFilters.jumpLinkName);
            if (currentFilters.year) params.append('year', currentFilters.year);
            const response = await fetch(`/api/records?${params.toString()}`);
            const data = await response.json();
            if (data.success) {
                displayRecords(data.records, data.pagination);
            } else {
                showError(data.error);
            }
        }

        // 显示扫码记录
        function displayRecords(records, pagination) {
            const recordsTable = document.getElementById('recordsTable');
            recordsTable.innerHTML = '';
            
            records.forEach(record => {
                const deviceInfo = record.deviceInfo || {};
                const userInfo = record.userInfo || {};
                const isSelected = selectedRecords.has(record.id);
                
                const deviceInfoHtml = `
                    <div class="device-info">
                        <span class="device-badge system">${deviceInfo.system || '未知'}</span>
                        <span class="device-badge software">${deviceInfo.software || '未知'}</span>
                        <span class="device-badge network">${deviceInfo.networkType || '未知'}</span>
                        <span class="device-badge device">${deviceInfo.deviceType || '未知'}</span>
                    </div>
                `;
                // 展示IP、坐标、百度和高德地址（始终显示详细地址和腾讯坐标）
                let ipDisplay = record.ip || '';
                let coordStr = '';
                if (record.location && record.location.location) {
                    const loc = record.location.location;
                    coordStr = `<br><span style='color:#888;font-size:12px;'>坐标：(${loc.lat}, ${loc.lng})</span>`;
                }
                if (record.baiduLocation && (record.baiduLocation.formatted_address || record.baiduLocation.business)) {
                    // 百度：只显示到区，business只取第一个
                    let addr = record.baiduLocation.formatted_address || '';
                    let business = record.baiduLocation.business || '';
                    let district = '';
                    if (addr) {
                        const match = addr.match(/^(.*?市.*?区)/);
                        if (match) {
                            district = match[1];
                        } else {
                            const match2 = addr.match(/^(.*?市.*?县)/);
                            if (match2) district = match2[1];
                        }
                    }
                    let businessName = business.split(',')[0] || '';
                    ipDisplay = `${district}${businessName ? businessName : ''}${coordStr}`;
                } else if (record.amapLocation && (record.amapLocation.addressComponent || record.amapLocation.formatted_address)) {
                    // 高德：显示省市区+道路/兴趣点
                    let ac = record.amapLocation.addressComponent || {};
                    let province = ac.province || '';
                    let city = ac.city || '';
                    let district = ac.district || '';
                    let street = ac.township || ac.street || '';
                    let poi = '';
                    if (record.amapLocation.pois && record.amapLocation.pois.length > 0) {
                        poi = record.amapLocation.pois[0].name;
                    }
                    let addr = `${province}${city}${district}${street}${poi}`;
                    if (!addr) addr = record.amapLocation.formatted_address || '';
                    ipDisplay = `${addr}${coordStr}`;
                } else if (coordStr) {
                    ipDisplay += coordStr;
                }
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><input type="checkbox" ${isSelected ? 'checked' : ''} onchange="toggleRecordSelection(${record.id}, this.checked)"></td>
                    <td>${new Date(record.scanTime).toLocaleString()}</td>
                    <td>${record.communityName}</td>
                    <td>${ipDisplay}</td>
                    <td>${deviceInfoHtml}</td>
                    <td>${record.jumpLinkName || ''}</td>
                    <td>
                        <div class="record-actions">
                            <button class="btn btn-danger btn-sm" onclick="deleteRecord(${record.id})">删除</button>
                        </div>
                    </td>
                `;
                recordsTable.appendChild(row);
            });
            
            // 更新全选复选框状态
            updateSelectAllCheckbox();
            
            // 显示分页
            displayPagination(pagination);
        }

        // 显示分页
        function displayPagination(pagination) {
            const paginationDiv = document.getElementById('pagination');
            paginationDiv.innerHTML = '';
            
            if (pagination.totalPages <= 1) return;
            
            const currentPage = pagination.page;
            const totalPages = pagination.totalPages;
            
            // 上一页
            if (currentPage > 1) {
                const prevBtn = document.createElement('button');
                prevBtn.className = 'btn btn-primary';
                prevBtn.textContent = '上一页';
                prevBtn.onclick = () => loadRecords(currentPage - 1);
                paginationDiv.appendChild(prevBtn);
            }
            
            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage) {
                    const span = document.createElement('span');
                    span.className = 'btn btn-primary';
                    span.textContent = i;
                    span.style.margin = '0 5px';
                    paginationDiv.appendChild(span);
                } else {
                    const btn = document.createElement('button');
                    btn.className = 'btn btn-warning';
                    btn.textContent = i;
                    btn.style.margin = '0 5px';
                    btn.onclick = () => loadRecords(i);
                    paginationDiv.appendChild(btn);
                }
            }
            
            // 下一页
            if (currentPage < totalPages) {
                const nextBtn = document.createElement('button');
                nextBtn.className = 'btn btn-primary';
                nextBtn.textContent = '下一页';
                nextBtn.onclick = () => loadRecords(currentPage + 1);
                paginationDiv.appendChild(nextBtn);
            }
        }

        // 删除单条记录
        async function deleteRecord(recordId) {
            const confirmed = await showConfirmDialog('确定要删除这条记录吗？');
            if (!confirmed) {
                return;
            }
            
            try {
                const response = await fetch(`/api/records/${recordId}`, {
                    method: 'DELETE'
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess('记录删除成功');
                    loadRecords(currentPage);
                    loadStatistics(); // 重新加载统计信息
                } else {
                    showError(data.error);
                }
            } catch (error) {
                console.error('删除记录失败:', error);
                showError('删除记录失败');
            }
        }

        // 删除筛选的记录
        async function deleteFilteredRecords() {
            const confirmed = await showConfirmDialog('确定要删除筛选条件下的所有记录吗？');
            if (!confirmed) {
                return;
            }
            
            try {
                const params = new URLSearchParams();
                if (currentFilters.communityId) {
                    params.append('communityId', currentFilters.communityId);
                }
                if (currentFilters.startDate) {
                    params.append('startDate', currentFilters.startDate);
                }
                if (currentFilters.endDate) {
                    params.append('endDate', currentFilters.endDate);
                }
                if (currentFilters.startTime) {
                    params.append('startTime', currentFilters.startTime);
                }
                if (currentFilters.endTime) {
                    params.append('endTime', currentFilters.endTime);
                }
                
                const response = await fetch(`/api/records/filtered?${params.toString()}`, {
                    method: 'DELETE'
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess(`成功删除 ${data.deletedCount} 条记录`);
            loadRecords(1);
                    loadStatistics(); // 重新加载统计信息
                } else {
                    showError(data.error);
                }
            } catch (error) {
                console.error('删除筛选记录失败:', error);
                showError('删除筛选记录失败');
            }
        }

        // 切换记录选择
        function toggleRecordSelection(recordId, isSelected) {
            if (isSelected) {
                selectedRecords.add(recordId);
            } else {
                selectedRecords.delete(recordId);
            }
            updateSelectAllCheckbox();
        }

        // 切换全选
        function toggleSelectAll() {
            const selectAllCheckbox = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('#recordsTable input[type="checkbox"]');
            
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
                const recordId = parseInt(checkbox.getAttribute('onchange').match(/\d+/)[0]);
                if (selectAllCheckbox.checked) {
                    selectedRecords.add(recordId);
                } else {
                    selectedRecords.delete(recordId);
                }
            });
        }

        // 更新全选复选框状态
        function updateSelectAllCheckbox() {
            const selectAllCheckbox = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('#recordsTable input[type="checkbox"]');
            
            if (checkboxes.length === 0) {
                selectAllCheckbox.checked = false;
                selectAllCheckbox.indeterminate = false;
                return;
            }
            
            const checkedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
            
            if (checkedCount === 0) {
                selectAllCheckbox.checked = false;
                selectAllCheckbox.indeterminate = false;
            } else if (checkedCount === checkboxes.length) {
                selectAllCheckbox.checked = true;
                selectAllCheckbox.indeterminate = false;
            } else {
                selectAllCheckbox.checked = false;
                selectAllCheckbox.indeterminate = true;
            }
        }

        // 删除选中的记录
        async function deleteSelectedRecords() {
            if (selectedRecords.size === 0) {
                showError('请选择要删除的记录');
                return;
            }
            
            const confirmed = await showConfirmDialog(`确定要删除选中的 ${selectedRecords.size} 条记录吗？`);
            if (!confirmed) {
                return;
            }
            
            try {
                const recordIds = Array.from(selectedRecords);
                console.log('准备删除记录ID:', recordIds);
                
                const response = await fetch('/api/records/batch', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        recordIds: recordIds
                    })
                });
                
                console.log('删除响应状态:', response.status);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                console.log('删除响应数据:', data);
                
                if (data.success) {
                    showSuccess(`成功删除 ${data.deletedCount} 条记录`);
                    selectedRecords.clear();
                    loadRecords(currentPage);
                    loadStatistics(); // 重新加载统计信息
                } else {
                    showError(data.error);
                }
            } catch (error) {
                console.error('删除选中记录失败:', error);
                showError('删除选中记录失败: ' + error.message);
            }
        }

        // 地区筛选变化时重新加载日期列表
        document.getElementById('filterCommunity').addEventListener('change', function() {
            loadAvailableDates();
        });

        // 导出地区统计
        async function exportCommunityStats() {
            try {
                const sortBy = document.getElementById('sortBy').value;
                const sortOrder = document.getElementById('sortOrder').value;
                const year = document.getElementById('communityFilterYear').value;
                const month = document.getElementById('communityFilterMonth').value;
                const date = document.getElementById('communityFilterDate').value;
                const jumpLinkName = document.getElementById('communityFilterJumpLinkName').value;
                const params = new URLSearchParams({ sortBy: sortBy, order: sortOrder });
                if (year) params.append('year', year);
                if (month) params.append('month', month);
                if (date) params.append('date', date);
                if (jumpLinkName) params.append('jumpLinkName', jumpLinkName);
                const response = await fetch(`/api/community-stats/export?${params.toString()}`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const blob = await response.blob();
                if (blob.size === 0) {
                    showError('导出的文件为空，请检查是否有数据');
                    return;
                }
                let filename = '地区统计';
                if (year) filename += `_${year}`;
                if (month) filename += `_${month}`;
                if (date) filename += `_${date}`;
                if (jumpLinkName) filename += `_${jumpLinkName}`;
                filename += `_${new Date().toISOString().split('T')[0]}.csv`;
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                showSuccess('地区统计导出成功');
            } catch (error) {
                console.error('导出地区统计失败:', error);
                showError('导出地区统计失败: ' + error.message);
            }
        }

        // 导出全部记录
        async function exportAllRecords() {
            try {
                console.log('开始导出全部记录');
                const params = new URLSearchParams();
                if (currentFilters.communityId) params.append('communityId', currentFilters.communityId);
                if (currentFilters.date) params.append('date', currentFilters.date);
                if (currentFilters.jumpLinkName) params.append('jumpLinkName', currentFilters.jumpLinkName);
                if (currentFilters.year) params.append('year', currentFilters.year);
                const response = await fetch(`/api/records/export?${params.toString()}`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const blob = await response.blob();
                if (blob.size === 0) {
                    showError('导出的文件为空，请检查是否有数据');
                    return;
                }
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `扫码记录_全部_${new Date().toISOString().split('T')[0]}.csv`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                showSuccess('全部记录导出成功');
            } catch (error) {
                console.error('导出全部记录失败:', error);
                showError('导出全部记录失败: ' + error.message);
            }
        }

        // 导出筛选记录
        async function exportFilteredRecords() {
            try {
                console.log('开始导出筛选记录');
                const params = new URLSearchParams();
                if (currentFilters.communityId) params.append('communityId', currentFilters.communityId);
                if (currentFilters.date) params.append('date', currentFilters.date);
                if (currentFilters.jumpLinkName) params.append('jumpLinkName', currentFilters.jumpLinkName);
                if (currentFilters.year) params.append('year', currentFilters.year);
                console.log('导出筛选参数:', params.toString());
                const response = await fetch(`/api/records/export?${params.toString()}`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const blob = await response.blob();
                if (blob.size === 0) {
                    showError('导出的文件为空，请检查是否有数据');
                    return;
                }
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `扫码记录_筛选_${new Date().toISOString().split('T')[0]}.csv`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                showSuccess('筛选记录导出成功');
            } catch (error) {
                console.error('导出筛选记录失败:', error);
                showError('导出筛选记录失败: ' + error.message);
            }
        }

        // 显示错误信息
        function showError(message) {
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error';
            errorDiv.textContent = message;
            
            const container = document.querySelector('.content.active');
            container.insertBefore(errorDiv, container.firstChild);
            
            setTimeout(() => {
                errorDiv.remove();
            }, 3000);
        }

        // 显示成功信息
        function showSuccess(message) {
            const successDiv = document.createElement('div');
            successDiv.className = 'success';
            successDiv.textContent = message;
            
            const container = document.querySelector('.content.active');
            container.insertBefore(successDiv, container.firstChild);
            
            setTimeout(() => {
                successDiv.remove();
            }, 3000);
        }

        // 渲染jumpLinks列表
        function renderJumpLinks(jumpLinks) {
            const container = document.getElementById('jumpLinksList');
            container.innerHTML = '';
            jumpLinks.forEach((item, idx) => {
                const row = document.createElement('div');
                row.style.display = 'flex';
                row.style.gap = '8px';
                row.style.marginBottom = '8px';
                row.innerHTML = `
                    <input type="text" placeholder="名称" value="${item.name || ''}" style="flex:1;" onchange="updateJumpLinkName(${idx}, this.value)">
                    <input type="url" placeholder="跳转链接" value="${item.url || ''}" style="flex:2;" onchange="updateJumpLinkUrl(${idx}, this.value)">
                    <button class="btn btn-danger btn-sm" onclick="removeJumpLink(${idx})">删除</button>
                `;
                container.appendChild(row);
            });
        }

        // 跳转链接操作
        let jumpLinksCache = [];
        function addJumpLink() {
            jumpLinksCache.push({ name: '', url: '' });
            renderJumpLinks(jumpLinksCache);
        }
        function removeJumpLink(idx) {
            jumpLinksCache.splice(idx, 1);
            renderJumpLinks(jumpLinksCache);
        }
        function updateJumpLinkName(idx, val) {
            jumpLinksCache[idx].name = val;
        }
        function updateJumpLinkUrl(idx, val) {
            jumpLinksCache[idx].url = val;
        }

        // 加载系统配置
        async function loadSystemConfig() {
            try {
                const response = await fetch('/api/system-config');
                const data = await response.json();
                if (data.success) {
                    const config = data.config;
                    jumpLinksCache = Array.isArray(config.jumpLinks) ? config.jumpLinks : [];
                    renderJumpLinks(jumpLinksCache);
                    document.getElementById('baseUrl').value = config.baseUrl || '';
                    document.getElementById('tencentMapKey').value = config.tencentMapKey || '';
                    document.getElementById('baiduMapAk').value = config.baiduMapAk || '';
                    showConfigStatus('配置加载成功', 'success');
                } else {
                    showConfigStatus('加载配置失败: ' + data.error, 'error');
                }
            } catch (error) {
                showConfigStatus('加载配置失败: ' + error.message, 'error');
            }
        }

        // 保存系统配置
        async function saveSystemConfig() {
            try {
                const baseUrl = document.getElementById('baseUrl').value.trim();
                const tencentMapKey = document.getElementById('tencentMapKey').value.trim();
                const baiduMapAk = document.getElementById('baiduMapAk').value.trim();
                if (!jumpLinksCache.length || jumpLinksCache.some(j => !j.name || !j.url)) {
                    showConfigStatus('请填写完整的名称和跳转链接', 'error');
                    return;
                }
                if (!baseUrl) {
                    showConfigStatus('请填写基础URL', 'error');
                    return;
                }
                const response = await fetch('/api/system-config', {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ jumpLinks: jumpLinksCache, baseUrl, tencentMapKey, baiduMapAk })
                });
                const data = await response.json();
                if (data.success) {
                    showConfigStatus('配置保存成功', 'success');
                    setTimeout(() => { loadSystemConfig(); }, 1000);
                    if (document.getElementById('jumpLinkSelect')) {
                        loadJumpLinksForQR();
                    }
                } else {
                    showConfigStatus('保存配置失败: ' + data.error, 'error');
                }
            } catch (error) {
                showConfigStatus('保存配置失败: ' + error.message, 'error');
            }
        }

        // 显示配置状态
        function showConfigStatus(message, type) {
            const statusEl = document.getElementById('configStatus');
            statusEl.textContent = message;
            statusEl.className = `config-status ${type}`;
            statusEl.style.display = 'block';
            
            setTimeout(() => {
                statusEl.style.display = 'none';
            }, 3000);
        }

        // 自定义确认对话框
        function showConfirmDialog(message) {
            return new Promise((resolve) => {
                const overlay = document.createElement('div');
                overlay.className = 'confirm-overlay';
                
                overlay.innerHTML = `
                    <div class="confirm-dialog">
                        <h3>确认操作</h3>
                        <p>${message}</p>
                        <div class="confirm-buttons">
                            <button class="confirm-btn cancel" onclick="closeConfirmDialog(false)">取消</button>
                            <button class="confirm-btn confirm" onclick="closeConfirmDialog(true)">确定</button>
                        </div>
                    </div>
                `;
                
                document.body.appendChild(overlay);
                
                // 添加ESC键关闭功能
                const handleEsc = (e) => {
                    if (e.key === 'Escape') {
                        closeConfirmDialog(false);
                    }
                };
                document.addEventListener('keydown', handleEsc);
                
                // 点击背景关闭
                overlay.addEventListener('click', (e) => {
                    if (e.target === overlay) {
                        closeConfirmDialog(false);
                    }
                });
                
                // 全局函数，用于按钮点击
                window.closeConfirmDialog = (result) => {
                    document.removeEventListener('keydown', handleEsc);
                    document.body.removeChild(overlay);
                    delete window.closeConfirmDialog;
                    resolve(result);
                };
            });
        }

        // 登出功能
        async function logout() {
            const confirmed = await showConfirmDialog('确定要退出登录吗？');
            if (!confirmed) {
                return;
            }
            // 清除本地登录状态
            localStorage.removeItem('isLoggedIn');
            localStorage.removeItem('username');
            window.location.href = '/login';
        }

        // 显示修改密码模态框
        function showChangePasswordModal() {
            document.getElementById('passwordModal').style.display = 'flex';
            document.getElementById('currentPassword').focus();
        }

        // 关闭修改密码模态框
        function closePasswordModal() {
            document.getElementById('passwordModal').style.display = 'none';
            document.getElementById('currentPassword').value = '';
            document.getElementById('newPassword').value = '';
            document.getElementById('confirmPassword').value = '';
            document.getElementById('passwordError').style.display = 'none'; // 隐藏错误提示
        }

        // 处理修改密码
        async function handleChangePassword(event) {
            event.preventDefault();
            
            const currentPassword = document.getElementById('currentPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            const username = localStorage.getItem('username') || 'admin';
            
            // 隐藏之前的错误提示
            document.getElementById('passwordError').style.display = 'none';
            
            if (newPassword !== confirmPassword) {
                document.getElementById('passwordError').textContent = '新密码和确认密码不一致';
                document.getElementById('passwordError').style.display = 'block';
                return;
            }
            
            if (newPassword.length < 6) {
                document.getElementById('passwordError').textContent = '新密码长度不能少于6位';
                document.getElementById('passwordError').style.display = 'block';
                return;
            }
            // 新密码与原密码一致校验
            if (newPassword === currentPassword) {
                document.getElementById('passwordError').textContent = '与原密码一致，请重新修改';
                document.getElementById('passwordError').style.display = 'block';
                return;
            }
            try {
                const response = await fetch('/api/change-password', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        username: username,
                        currentPassword: currentPassword,
                        newPassword: newPassword
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showSuccess('密码修改成功，请重新登录');
                    closePasswordModal();
                    setTimeout(() => {
                        logout();
                    }, 1200);
                } else {
                    document.getElementById('passwordError').textContent = data.error || '密码修改失败';
                    document.getElementById('passwordError').style.display = 'block';
                }
            } catch (error) {
                console.error('修改密码失败:', error);
                document.getElementById('passwordError').textContent = '修改密码失败';
                document.getElementById('passwordError').style.display = 'block';
            }
        }

        // 点击模态框背景关闭
        document.getElementById('passwordModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closePasswordModal();
            }
        });

        // ESC键关闭模态框
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closePasswordModal();
            }
        });

        // 加载可用年份和日期
        async function loadAvailableYearsAndDates() {
            try {
                const communityId = document.getElementById('filterCommunity').value;
                const params = new URLSearchParams();
                if (communityId) {
                    params.append('communityId', communityId);
                }
                const response = await fetch(`/api/records/years-dates?${params.toString()}`);
                const data = await response.json();
                if (data.success) {
                    // 填充年份下拉框
                    const yearSelect = document.getElementById('filterYear');
                    yearSelect.innerHTML = '<option value="">全部年份</option>';
                    if (data.years && data.years.length > 0) {
                        data.years.forEach(year => {
                            const option = document.createElement('option');
                            option.value = year;
                            option.textContent = year;
                            yearSelect.appendChild(option);
                        });
                    }
                    // 填充日期下拉框
                    availableDates = data.dates || [];
                    updateDateSelects();
                }
            } catch (error) {
                console.error('加载年份和日期失败:', error);
            }
        }

        // 更新日期选择框（支持年份筛选）
        function updateDateSelects() {
            const filterDateSelect = document.getElementById('filterDate');
            const year = document.getElementById('filterYear').value;
            filterDateSelect.innerHTML = '<option value="">全部日期</option>';
            availableDates.forEach(date => {
                let text = date;
                if (year) {
                    text = date.substring(5); // 只显示月-日
                }
                const option = document.createElement('option');
                option.value = date;
                option.textContent = text;
                filterDateSelect.appendChild(option);
            });
        }

        // 年份变化时，刷新日期下拉框
        if (document.getElementById('filterYear')) {
            document.getElementById('filterYear').addEventListener('change', function() {
                updateDateSelects();
            });
        }

        // 页面加载时加载可用年份和日期
        if (document.getElementById('filterYear')) {
            document.addEventListener('DOMContentLoaded', function() {
                loadAvailableYearsAndDates();
            });
        }

        // 加载二维码小程序下拉框
        async function loadJumpLinksForQR() {
            try {
                const response = await fetch('/api/system-config');
                const data = await response.json();
                if (data.success) {
                    const jumpLinks = Array.isArray(data.config.jumpLinks) ? data.config.jumpLinks : [];
                    const select = document.getElementById('jumpLinkSelect');
                    select.innerHTML = '<option value="">请选择跳转链接</option>';
                    jumpLinks.forEach(j => {
                        const option = document.createElement('option');
                        option.value = j.name;
                        option.textContent = j.name;
                        select.appendChild(option);
                    });
                }
            } catch (error) {
                // ignore
            }
        }

        // 页面加载时加载小程序下拉框
        if (document.getElementById('jumpLinkSelect')) {
            document.addEventListener('DOMContentLoaded', function() {
                loadJumpLinksForQR();
            });
        }

        // 加载小程序名称下拉框
        async function loadJumpLinksForFilter() {
            try {
                const response = await fetch('/api/system-config');
                const data = await response.json();
                if (data.success) {
                    const jumpLinks = Array.isArray(data.config.jumpLinks) ? data.config.jumpLinks : [];
                    const select = document.getElementById('filterJumpLinkName');
                    select.innerHTML = '<option value="">全部跳转链接</option>';
                    jumpLinks.forEach(j => {
                        const option = document.createElement('option');
                        option.value = j.name;
                        option.textContent = j.name;
                        select.appendChild(option);
                    });
                }
            } catch (error) {}
        }
        if (document.getElementById('filterJumpLinkName')) {
            document.addEventListener('DOMContentLoaded', function() {
                loadJumpLinksForFilter();
            });
        }

        // 加载小程序名称下拉框（地区统计）
        async function loadCommunityJumpLinks() {
            try {
                const response = await fetch('/api/system-config');
                const data = await response.json();
                if (data.success) {
                    const jumpLinks = Array.isArray(data.config.jumpLinks) ? data.config.jumpLinks : [];
                    const select = document.getElementById('communityFilterJumpLinkName');
                    select.innerHTML = '';
                    jumpLinks.forEach(j => {
                        const option = document.createElement('option');
                        option.value = j.name;
                        option.textContent = j.name;
                        select.appendChild(option);
                    });
                    if (jumpLinks.length > 0) {
                        select.value = jumpLinks[0].name;
                        loadCommunityStats();
                    }
                }
            } catch (error) {}
        }
        if (document.getElementById('communityFilterJumpLinkName')) {
            document.addEventListener('DOMContentLoaded', function() {
                loadCommunityJumpLinks();
            });
        }

        // 自动筛选逻辑
        function onStatisticsFilterChange() {
            const communityId = document.getElementById('filterCommunity').value;
            const filterDate = document.getElementById('filterDate').value;
            const jumpLinkName = document.getElementById('filterJumpLinkName').value;
            const year = document.getElementById('filterYear').value;
            currentFilters = {};
            if (communityId) currentFilters.communityId = communityId;
            if (filterDate) currentFilters.date = filterDate;
            if (jumpLinkName) currentFilters.jumpLinkName = jumpLinkName;
            if (year) currentFilters.year = year;
            loadRecords(1);
            loadStatistics();
        }
    </script>
</body>
</html> 